package com.zikao.common.service;

import lombok.extern.slf4j.Slf4j;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

/**
 * @Author: Likaisheng
 * @Description: 该抽象类不用实现，实际使用时，匿名实现就行
 * @Date: Created in 15:55:25 2021-03-20
 * @Modified By:
 */
@Slf4j
public abstract class EmailService {
    static String myEmailAccount = "3346479517@qq.com";
    static String myEmailPassword = "wcdbltzkzscncgif";
    static String myEmailSMTPHost = "smtp.qq.com";

    private Properties props;
    private Session session;

    public EmailService(){
        props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.smtp.host", myEmailSMTPHost);
        props.setProperty("mail.smtp.auth", "true");

        final String smtpPort = "465";
        props.setProperty("mail.smtp.port", smtpPort);
        props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.socketFactory.port", smtpPort);
    }

    public void sendMail() throws MessagingException, UnsupportedEncodingException {
        try{
            // 与QQ的SMTP服务器建立会话
            session = Session.getInstance(props);
            session.setDebug(true);
            Transport transport = session.getTransport();

            transport.connect(myEmailAccount, myEmailPassword);
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(myEmailAccount, "北京自考社区网站", "UTF-8"));
            createMimeMessage(message);

            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
        }catch (Exception e){
            log.error("邮件发送失败：",e);
            throw e;
        }
    }

    // 自定义邮件内容
    public abstract void createMimeMessage(MimeMessage message) throws UnsupportedEncodingException, MessagingException;
}
